package com.octopus.core.downloader.proxy;

import com.octopus.core.Request;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import lombok.NonNull;

/**
 * 提供绑定主机的代理服务器
 *
 * @author yang_shoulai@hoperun.com
 * @date 2019/08/03
 */
public class HostBindProxyProvider implements ProxyProvider {

  private Map<String, Proxy> proxies = new HashMap<>();

  public HostBindProxyProvider() {
  }

  public HostBindProxyProvider(@NonNull Map<String, Proxy> proxies) {
    this.proxies.putAll(proxies);
  }

  /**
   * 增加代理服务器
   *
   * @param bindHost 绑定的主机
   * @param proxy 代理服务器
   */
  public void addProxy(String bindHost, Proxy proxy) {
    this.proxies.put(bindHost, proxy);
  }

  @Override
  public Proxy provide(Request request) {
    String url = request.url();
    try {
      String host = new URL(url).getHost();
      return this.proxies.get(host);
    } catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
  }
}
